package Fly.example.service.impl;

import Fly.example.common.R;
import Fly.example.dto.DishDto;
import Fly.example.pojo.Dish;
import Fly.example.mapper.DishMapper;
import Fly.example.pojo.DishFlavor;
import Fly.example.service.IDishFlavorService;
import Fly.example.service.IDishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author 陽Fly
 * @since 2025-06-14
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private IDishFlavorService iDishFlavorService;
    //新增菜品同时保存对应的口味数据
    @Override
    @Transactional//事务管理
    public void SaveWithflavor(DishDto dishDto) {
        //保存基本信息到菜品表（dish）
        this.save(dishDto);
        //处理还没有添加dishid
        Long dishid = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishid);
            return item;
        }).collect(Collectors.toList());
        //保存菜品口味到dish_flavor
        iDishFlavorService.saveBatch(flavors);
    }

    /*
     * 用于查询菜品以及对应口味的信息
     * */
    @Override
    public DishDto getDishWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        Long dishId = dish.getId();
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<DishFlavor>();
        queryWrapper.eq(DishFlavor::getDishId, dishId);
        List<DishFlavor> flavors = iDishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    public void updataWithflavor(DishDto dishdto) {
        List<DishFlavor> flavors = dishdto.getFlavors();
        //跟新菜品表
        this.updateById(dishdto);
        //先清理当前菜品的口味，再添加当前菜品的口味
        //清理
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishdto.getId());
        iDishFlavorService.remove(queryWrapper);
        //添加
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishdto.getId());
            return item;
        }).collect(Collectors.toList());
        iDishFlavorService.saveBatch(flavors);
    }
}
